package com.ebt.m.proposal_v2.retrofit;

import android.text.TextUtils;

import org.json.JSONException;
import org.json.JSONObject;

/**
 * 请求固定错误
 *
 * @author archer.qi
 *         Created on 2017/5/18.
 */
public class ErrorGenerator {

    /**
     * 生成一个Error对象
     *
     * @param code
     * @param message
     * @param type
     * @return
     */
    public static ResponseError createError(String code, String message, String type) {
        ResponseError error = new ResponseError();
        error.code = code;
        error.message = message;
        error.type = type;
        return error;
    }

    /**
     * 生成一个带有默认错误信息的请求Error
     *
     * @return
     */
    public static ResponseError requestError() {
        final String code = "-1";
        final String message = "a request error happened";
        final String type = "requestError";
        return createError(code, message, type);
    }

    /**
     * 生成一个请求Error
     *
     * @return
     */
    public static ResponseError requestError(String msg) {
        final String code = "-1";
        final String type = "requestError";
        return createError(code, msg, type);
    }

    /**
     * 生成一个请求Error
     *
     * @return
     */
    public static ResponseError nullDataError() {
        final String code = "-101";
        final String message = "null data returned";
        final String type = "NullDataError";
        return createError(code, message, type);
    }

    /**
     * 生成一个网络Error
     *
     * @return
     */
    public static ResponseError networkError() {
        final String code = "-102";
        final String message = "no network connected";
        final String type = "NetworkError";
        return createError(code, message, type);
    }

    /**
     * 解析ErrorJson字符串
     *
     * @param errorJsonMsg
     * @return
     */
    public static ResponseError parseErrorJson(String errorJsonMsg) {
        if (TextUtils.isEmpty(errorJsonMsg)) {
            return null;
        }
        try {
            JSONObject errorObj = new JSONObject(errorJsonMsg);
            if (errorObj != null) {
                return createError(errorObj.optString("code"),
                        errorObj.optString("message"),
                        errorObj.optString("type"));
            }
        } catch (JSONException e) {
        }
        return null;
    }

}
